package com.xys.auth.service.impl;

import com.xys.auth.bean.Permission;
import com.xys.auth.bean.Role;
import com.xys.auth.bean.UserInfo;
import com.xys.auth.mapper.UserMapper;
import com.xys.auth.service.IUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.AccountNotFoundException;
import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;
    /**
     * 在用户登录的时候。/login
     * 第一步，根据用户名查询用户的信息
     * 第二步，将数据库中的用户信息加载为UserDetails
     * 第三步，通过密码Encoder比较前端输入的密码和数据库中的密码进行匹配
     * 第四步，如果匹配成功，Spring Security 会把UserDetails这个对象放到Session里面
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userMapper.findByUsername(username);

        System.out.println(userInfo);
        if(userInfo != null){
            List<SimpleGrantedAuthority> authorities = getAuthority(userInfo.getRoles());
            User user = new User(
                    userInfo.getUsername(),
                    userInfo.getPassword(),
                    userInfo.getStatus() == 0?false:true,
                    true,
                    true,
                    true,
                    authorities
            );
            System.out.println(user);
            return user;
        }else{
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }

    @Override
    public List<UserInfo> findAll() {
        return userMapper.findAll();
    }

    @Override
    public int save(UserInfo userInfo) {
        return userMapper.save(userInfo);
    }

    @Override
    public UserInfo findById(String id) {
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public void addRoleToUser(String userId, String[] ids) {

        for (int i = 0; i < ids.length; i++) {
            userMapper.addRoleToUser(userId,ids[i]);
        }
    }

    /**
     * 读取角色列表，加载为权限列表
     * @param roles
     * @return
     */
    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        for(Role role : roles){
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));

            for(Permission permission:role.getPermissions()){
                authorities.add(new SimpleGrantedAuthority(permission.getUrl()));
            }
        }
        return authorities;
    }
}
